from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from ..models import FileStorage

cart_bp = Blueprint('cart', __name__)
carts = FileStorage('carts.json')
products = FileStorage('products.json')

@cart_bp.route('/cart', methods=['POST'])
@jwt_required()
def add_to_cart():
    username = get_jwt_identity()
    data = request.get_json()
    product_id = data.get('product_id')
    quantity = data.get('quantity', 1)
    
    # 验证商品是否存在
    product = products.find_one('id', product_id)
    if not product:
        return jsonify({'message': '商品不存在'}), 404
    
    # 获取用户购物车
    cart = carts.find_one('username', username) or {
        'username': username,
        'items': []
    }
    
    # 检查商品是否已在购物车中
    cart_item = next(
        (item for item in cart['items'] if item['product_id'] == product_id),
        None
    )
    
    if cart_item:
        cart_item['quantity'] += quantity
    else:
        cart['items'].append({
            'product_id': product_id,
            'quantity': quantity,
            'price': product['price']
        })
    
    # 计算总数和总价
    total_items = sum(item['quantity'] for item in cart['items'])
    total_price = sum(item['quantity'] * item['price'] for item in cart['items'])
    
    # 更新购物车
    if not cart.get('id'):
        carts.insert(cart)
    else:
        carts.update('username', username, cart)
    
    return jsonify({
        'total_items': total_items,
        'total_price': total_price
    })